﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Threading;

namespace XMM.Dialoges.Library
{
    /// <summary>
    /// Interaktionslogik für HistoryViewer.xaml
    /// </summary>
    public partial class HistoryViewer : Window
    {
        Mutex mutLoadRecords = new Mutex();

        int iMaxRecords = 10;

        ObservableCollection<Objects.PlaybackHistoryRecord> LastRecords
        { get { return _LastRecords; } }

        ObservableCollection<Objects.PlaybackHistoryRecord> _LastRecords = new ObservableCollection<Objects.PlaybackHistoryRecord>();

        XMM.Library ParentMainWindow;

        int iSelectedAudienceID = 0;

        public HistoryViewer(XMM.Library dlgParentMainWindow)
        {
            InitializeComponent();

            ParentMainWindow = dlgParentMainWindow;
            iSelectedAudienceID = ParentMainWindow.SelectedAudition.AuditionID;
        }

        public void loadAudiences()
        {
            cmbAudiences.Items.Clear();

            List<Objects.Audition> lAudiences = Objects.Audition.getAllAuditions();

            foreach (Objects.Audition oAudience in lAudiences)
            {
                cmbAudiences.Items.Add(oAudience);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            mutLoadRecords = new Mutex();
            loadAudiences();
            loadRecords();
        }

        public void loadRecords()
        {
            _LastRecords = new ObservableCollection<Objects.PlaybackHistoryRecord>();
            Thread thLoadingThread = new Thread(new ThreadStart(ProcessLoading));
            thLoadingThread.Start();
        }

        private void ProcessLoading()
        {
            if (mutLoadRecords.WaitOne(1000))
            {
                Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Lade History-Einträge...", true });

                if (iSelectedAudienceID == 0)
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    var vRecords = (from records in dbConnection.t_history orderby records.ID descending select records.ID).Take(iMaxRecords);

                    int iCurrentRecord = 1;

                    while (iCurrentRecord <= iMaxRecords)
                    {
                        foreach (int iRecordID in vRecords)
                        {
                            Dispatcher.Invoke(new addRecordCallback(addRecord), new object[] { new Objects.PlaybackHistoryRecord(iRecordID) });
                            ++iCurrentRecord;
                        }

                        break;
                    }
                }
                else
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    var vRecords = (from records in dbConnection.t_history where records.AudienceID == iSelectedAudienceID orderby records.ID descending select records.ID).Take(iMaxRecords);

                    int iCurrentRecord = 1;

                    while (iCurrentRecord <= iMaxRecords)
                    {
                        foreach (int iRecordID in vRecords)
                        {
                            Dispatcher.Invoke(new addRecordCallback(addRecord), new object[] { new Objects.PlaybackHistoryRecord(iRecordID) });
                            ++iCurrentRecord;
                        }

                        break;
                    }
                }

                Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Bereit...", false });

                mutLoadRecords.ReleaseMutex();
            }
        }

        private void setStatus(string sMessage, bool bEnableMarquee)
        {
            lblStatus.Content = sMessage;
            pbStatus.IsIndeterminate = bEnableMarquee;
        }

        private delegate void setStatusCallback(string sMessage, bool bEnableMarquee);

        private void addRecord(Objects.PlaybackHistoryRecord oRecord)
        {
            _LastRecords.Add(oRecord);
            lvRecords.ItemsSource = LastRecords;
            lvRecords.Items.Refresh();
        }

        private delegate void addRecordCallback(Objects.PlaybackHistoryRecord oRecord);

        private void lvRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lvRecords.SelectedIndex > -1)
            {
                btnPlaySelected.IsEnabled = true;

                Objects.PlaybackHistoryRecord oSelectedRecord = (Objects.PlaybackHistoryRecord)lvRecords.SelectedItem;

                Control ctlItemDetails = new Control();

                grdItemDetails.Children.Clear();

                switch (oSelectedRecord.MediaType)
                {
                    case 1:
                        ctlItemDetails = new Controls.Library.Details_Movie(oSelectedRecord.MediaID);
                        break;
                    case 2:
                        ctlItemDetails = new Controls.Library.Details_Episode(null, oSelectedRecord.MediaID);
                        break;
                    default:
                        break;
                }

                grdItemDetails.Children.Add(ctlItemDetails);
            }
            else
            {
                btnPlaySelected.IsEnabled = false;
                grdItemDetails.Children.Clear();
            }
        }

        private void btnPlaySelected_Click(object sender, RoutedEventArgs e)
        {
            if (lvRecords.SelectedIndex > -1)
            {
                Objects.PlaybackHistoryRecord oSelectedRecord = (Objects.PlaybackHistoryRecord)lvRecords.SelectedItem;

                switch (oSelectedRecord.MediaType)
                {
                    case 1:
                        Objects.Movie oSelectedMovie = new Objects.Movie(oSelectedRecord.MediaID);
                        ParentMainWindow.lblStatus.Content = "Es läuft \"" + oSelectedMovie.Name + " (" + oSelectedMovie.Year.ToString() + ")...";
                        ParentMainWindow.pbStatus.IsIndeterminate = true;

                        ParameterizedThreadStart ptsPlayMovie = new ParameterizedThreadStart(ParentMainWindow.startVLCPlayerMovie);
                        Thread thPlayMovie = new Thread(ptsPlayMovie);
                        thPlayMovie.Start(oSelectedMovie);
                        Close();
                        /*
                        ParentMainWindow.startVLCPlayerMovie(oSelectedMovie);
                        Close();
                        */
                        break;
                    case 2:
                        Objects.SeriesEpisode oSelectedEpisode = new Objects.SeriesEpisode(oSelectedRecord.MediaID);
                        Objects.Series oSeries = new Objects.Series(oSelectedEpisode.SeriesID);
                        Objects.SeriesSeason oSeason = new Objects.SeriesSeason(oSelectedEpisode.SeasonID);
                        ParentMainWindow.lblStatus.Content = "Es läuft: " + oSeries.Name + " S" + oSeason.Number.ToString() + " E" + oSelectedEpisode.EpisodeNo.ToString() + " - \"" + oSelectedEpisode.Name + "\"...";
                        ParentMainWindow.pbStatus.IsIndeterminate = true;
                        /*
                        ParameterizedThreadStart ptsPlayEpisode = new ParameterizedThreadStart(ParentMainWindow.startVLCPlayerEpisode);
                        Thread thPlayEpisode = new Thread(ptsPlayEpisode);
                        thPlayEpisode.Start(oSelectedEpisode);
                        */
                        /*
                        ParentMainWindow.startVLCPlayerEpisode(oSelectedEpisode);
                        Close();
                         * */
                        Close();
                        break;
                }
            }
        }

        private void btnExitHistory_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
